package com.aaa.controller;

import com.aaa.entity.Users;
import com.aaa.service.UsersService;
import com.aaa.util.Constants;
import com.aaa.util.DefaultMsg;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 查询所有用户信息
     */
    @RequestMapping("/listAll")
    public PageInfo<Users> listAll(String keyword, Integer currentPage, Integer pageSize){
        PageHelper.startPage(currentPage,pageSize);
        QueryWrapper<Users> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("username",keyword);
        List<Users> list=usersService.list(queryWrapper);

        PageInfo<Users> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }
    @RequestMapping("/saveOrUpdate")
    public DefaultMsg saveOrUpdate(Users user){
        DefaultMsg defaultMsg=new DefaultMsg();
        user.setPassword(passwordEncoder.encode(Constants.DEFAULT_PASSWORD));
        boolean b=usersService.saveOrUpdate(user);
        if (!b){
            defaultMsg.setSuccess(0);
            defaultMsg.setError("操作失败");
        }
        return defaultMsg;
    }
    @RequestMapping("/upload")
    public DefaultMsg upload(MultipartFile file){
        System.out.println(1111111);
        DefaultMsg defaultMsg=new DefaultMsg();
        //声明要上传的文件夹
        String dir="D:/upload_374/head/";
        //生成唯一的保存文件名
        String saveName= UUID.randomUUID().toString();
        File saveFile=new File(dir+saveName);
        try{
            file.transferTo(saveFile);
            defaultMsg.setTarget(saveName);
        } catch (IOException e) {
            e.printStackTrace();
            defaultMsg.setSuccess(0);
            defaultMsg.setError("上传失败");
        }

        //file.transferTo();
        return defaultMsg;
    }

    public static void main(String[] args) {
        System.out.println(UUID.randomUUID().toString());
    }

}
